package com.ruoyi.framework.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.satoken.StpWxUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author zouhuu
 * @description [Sa-Token 权限认证] 配置类
 * @date 2022/06/15 15:32:59
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    //    // 注册拦截器
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        // 注册Sa-Token的路由拦截器
//        registry.addInterceptor(new SaRouteInterceptor())
//                // 拦截 APP或小程序的 所有请求
//                .addPathPatterns("/api/**")
//                // 排除 APP或小程序的 认证授权请求，如登录等
//                .excludePathPatterns("/api/**/loginWx");
//    }
// 注册Sa-Token的注解拦截器，打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handle -> {
                    SaRouter.notMatch("/api/**").check(r->StpUtil.checkLogin());
                    SaRouter.match("/api/**").check(r-> StpWxUtils.checkLogin());
                }))
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/client/getVersion","/api/user/loginWx",
                        "/captchaImage",
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/profile/**",
                        "/common/download**",
                        "/common/download/resource**",
                        "/swagger-ui.html",
                        "/swagger-resources/**",
                        "/webjars/**",
                        "/*/api-docs",
                        "/druid/**");
    }

    // 配置全局异常处理
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new HandlerExceptionResolver() {
            @Override
            public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
                if (ex instanceof NotLoginException) {
                    // 设置响应状态码为401
                    response.setStatus(HttpStatus.UNAUTHORIZED);
                    // 可以在这里写入JSON响应体等
                    try {
                        response.getWriter().print("{\"code\":401,\"msg\":\"未授权\"}");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return new ModelAndView();
                }
                // 其他异常处理逻辑...
                return null;
            }
        });
    }
}
